import re
import ollama
from configparser import ConfigParser


# NOTE:
# 能用是能用, 就是屁话多, 经常不能直接返回相似度
# 依赖ollama, 成也ollama, 败也ollama


class TextScoreLlama2Ollama():
    _instance = None
    _model_name = None

    def __init__(self, path_config):
        config = ConfigParser()
        config.read(path_config, encoding='utf-8')
        self._MODEL_NAME = config.get('default', 'llama_ollama_name')
        print("llama_ollama_name from:", self._MODEL_NAME)
        if self._model_name == None:
            self._model_name = self._MODEL_NAME
            print("init model llama_ollama_name: " + self._model_name)

    def __new__(cls, path_config):
        # print("__new__")
        if cls._instance is None:
            instance = super().__new__(cls)
            instance.__init__(path_config)  # 如果需要初始化操作
            cls._instance = instance
        return cls._instance

    def similar_text_1(self, text1, text2):
        response = ollama.chat(model=self._model_name, messages=[
            {
                "role": "system",
                "content": f"Calculate the similarity between the following two paragraphs and return only the numerical value between 0 and 1.\n"
                           f"Paragraph 1: {text1}\n"
                           f"Paragraph 2: {text2}"
            }
        ])
        # 提取相似度值
        similar_str = response['message']['content']
        similar_val = None
        match = re.search(r'^(\d+(\.\d+)?)$', similar_str.strip())
        if match:
            similar_val = float(match.group(1))
        return similar_str, similar_val

    def similar_text_2(self, text1, text2):
        response = ollama.chat(model=self._model_name, messages=[
            {"role": "system", "content": "calculate similarity between the content of paragraph 1 and paragraph 2. "
                                          "The returned content must be: similarity=numerical value, "
                                          "without any redundant output. "
                                          "\nparagraph 1:" + text1 +
                                          "\nparagraph 2:" + text2},
        ])
        # 提取相似度值
        similar_str = response['message']['content']
        similar_value = None
        match = re.search(r'similarity=(\d+(\.\d+)?)', similar_str)
        if match:
            similar_value = float(match.group(1))
        return similar_str, similar_value

    def similar_text(self, text1, text2):
        similar_str, similar_value = self.similar_text_1(text1, text2)
        if similar_value is None:
            similar_str, similar_value = self.similar_text_2(text1, text2)
        return similar_str, similar_value





if __name__ == '__main__':
    gpt1 = TextScoreLlama2Ollama('../files/config.inf')
    # th1.testOllamaTranslate()
    # th1.testTranslate()
    text1 = f"这次通过VR虚拟实验室进行的一系列关于反相器的实验，体验了从原理设计，版图设计，芯片制作，最后到芯片封装测试一系列完整的流程，了解到了集成芯片制作的总体思路和具体技术，收获颇深。"
    text2 = f"完成反相器制造，学习集成电路设计制造、测试和流程。"
    similar_str, similar_value = gpt1.similar_text_1(text1, text2)
    print("======================================================")
    print("similar_value:", similar_value)
    print("similar_str:", similar_str)
    similar_str, similar_value = gpt1.similar_text_2(text1, text2)
    print("======================================================")
    print("similar_value:", similar_value)
    print("similar_str:", similar_str)
    similar_str, similar_value = gpt1.similar_text(text1, text2)
    print("======================================================")
    print("similar_value:", similar_value)
    print("similar_str:", similar_str)
